package com.qfmy.interceptor;


import common.exception.BaseException;
import common.login.LoginUser;
import common.login.LoginUserHolder;
import common.result.ResultCodeEnum;
import common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.interceptor
 * @date 2025/2/28
 * @description webApp的拦截器
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class webAppInterceptor implements HandlerInterceptor {


    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否为WebSocket握手请求
        String upgradeHeader = request.getHeader("Upgrade");
        if ("websocket".equalsIgnoreCase(upgradeHeader)) {
            log.info("WebSocket握手请求，跳过Token验证");
            return true; // 放行WebSocket请求
        }

        //从请求头里面token
        String token = request.getHeader("access-token");
        //判断token是否为空
        if (token != null) {
            //解析token
            Claims claims = JwtUtil.parseToken(token);
            //获取用户信息
            String phone = (String) claims.get("phone");
            String username = (String) claims.get("username");
            Long userId = Long.valueOf((Integer) claims.get("userId"));
            //创建LoginUser对象
            LoginUser loginUser = new LoginUser(phone, userId,username);
            //将用户信息保存在线程里面
            LoginUserHolder.setLoginUser(loginUser);
        }else
        {
            //返回错误信息
            throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        return true;
    }

    /**
     * 在请求处理之后进行调用（Controller方法调用之后）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程里面的用户信息
        LoginUserHolder.removeLoginUser();
    }

}
